import { defineStore } from 'pinia'
import axios from 'axios'

export const useVideoStore = defineStore('video', {
  state: () => ({
    status: 'stopped', // running, stopped, error
    rtspUrl: 'rtsp://admin:admin@192.168.1.100:554/stream1',
    segmentDuration: 2,
    segmentMaxFiles: 10,
    loading: false,
    error: null
  }),

  getters: {
    isRunning: (state) => state.status === 'running',
    isStopped: (state) => state.status === 'stopped',
    hasError: (state) => state.error !== null
  },

  actions: {
    async fetchStatus() {
      try {
        this.loading = true
        const response = await axios.get('/api/status')
        this.status = response.data.status
        this.rtspUrl = response.data.rtspUrl
        this.error = null
      } catch (error) {
        console.error('Failed to fetch status:', error)
        this.error = error.message
      } finally {
        this.loading = false
      }
    },

    async startStream() {
      try {
        this.loading = true
        this.error = null
        await axios.post('/api/start')
        await this.fetchStatus()
      } catch (error) {
        console.error('Failed to start stream:', error)
        this.error = error.response?.data?.error || error.message
      } finally {
        this.loading = false
      }
    },

    async stopStream() {
      try {
        this.loading = true
        this.error = null
        await axios.post('/api/stop')
        await this.fetchStatus()
      } catch (error) {
        console.error('Failed to stop stream:', error)
        this.error = error.response?.data?.error || error.message
      } finally {
        this.loading = false
      }
    },

    async updateConfig(config) {
      try {
        this.loading = true
        this.error = null
        await axios.post('/api/config', config)
        
        // 更新本地状态
        if (config.rtspUrl) this.rtspUrl = config.rtspUrl
        if (config.segmentDuration) this.segmentDuration = config.segmentDuration
        if (config.segmentMaxFiles) this.segmentMaxFiles = config.segmentMaxFiles
        
        await this.fetchStatus()
      } catch (error) {
        console.error('Failed to update config:', error)
        this.error = error.response?.data?.error || error.message
      } finally {
        this.loading = false
      }
    },

    clearError() {
      this.error = null
    }
  }
})
